<template>
  <!--  查询 -->
  <div class="query-container">
    <el-input placeholder="请输入客户姓名" style="width:200px" v-model="queryName" class="input-style"></el-input>
    <el-button @click="queryByName" type="success" plain class="button-style query-button">查询</el-button>
    <el-button @click="showCustomerDialog" type="primary" style="width: 100px; margin-left: 50px;font-weight: bolder; font-size: 16px" class="button-style register-button">
      登&emsp;记
    </el-button>
    <el-select v-model="statusFilter" placeholder="请选择客户状态" style="width:100px; margin-left: 50px">
      <el-option label="全部" value="all"></el-option>
      <el-option label="在住" value="in"></el-option>
      <el-option label="退住" value="out"></el-option>
    </el-select>
  </div>
  <!--  显示所有客户信息 table自动循环-->
  <div class="error-message-container">{{errorMessage}}</div>
  <el-table :data="customerList" class="customer-table">
    <el-table-column label="序号" type="index" width="60px"></el-table-column>
    <el-table-column prop="customerName" label="客户姓名" width="80px"></el-table-column>
    <el-table-column prop="customerSex" label="性别" width="80px">
      <template #default="scope">
        {{scope.row.customerSex === 0?'男':'女'}}
      </template>
    </el-table-column>
    <el-table-column prop="customerAge" label="年龄" width="80px"></el-table-column>
    <el-table-column prop="idcard" label="身份证号" width="220px"></el-table-column>
    <el-table-column prop="buildingNo" label="所属楼房" width="80px"></el-table-column>
    <el-table-column prop="checkinDate" label="入住日期" width="120px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="expirationDate" label="合同到期时间" width="120px" :formatter="formatDate"></el-table-column>
    <el-table-column prop="contactTel" label="联系电话" width="120px"></el-table-column>
    <el-table-column prop="familyMember" label="家属" width="80px"></el-table-column>
    <el-table-column prop="attention" label="备注" width="120px"></el-table-column>
    <el-table-column  label="操作">
      <template #default="scope">
        <el-button type="primary" @click="showEditDialog(scope.row.id)" class="button-style edit-button">修改</el-button>
        <el-button type="danger" @click="removeOne(scope.row.id)" class="button-style delete-button">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="example-pagination-block">
    <el-pagination background
                   v-model:current-page="pageContains.pageNum"
                   v-model:page-size="pageContains.pageSize"
                   :page-sizes="[10,20,30,50,100]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="pageContains.total"
                   @size-change="handleSizeChange"
                   @current-change="handlePageChange"
                   class="pagination-style"
    />
  </div>

  <!--  客户信息对话框 -->
  <el-dialog v-model="customerDialog" :title="dialogTitle" class="customer-dialog">
    <el-form :model="curCustomer" class="customer-form">
      <el-form-item label="客户姓名">
        <el-col :span="11">
          <el-input v-model="curCustomer.customerName" class="input-style"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="性&emsp;&emsp;别">
        <el-col :span="11">
          <el-select v-model="curCustomer.customerSex">
            <el-option
                v-for="item in sexOptions"
                :label="item.label"
                :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="年&emsp;&emsp;龄">
        <el-col :span="11">
          <el-input v-model="curCustomer.customerAge" class="input-style"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="身份证号">
        <el-col :span="11">
          <el-input v-model="curCustomer.idcard" class="input-style"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="所住楼房">
        <el-col :span="11">
          <el-input v-model="curCustomer.buildingNo" class="input-style"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="入住日期">
        <el-col :span="11">
          <el-date-picker v-model="curCustomer.checkinDate"></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="合同到期时间">
        <el-col :span="11">
          <el-date-picker v-model="curCustomer.expirationDate"></el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-col :span="11">
          <el-input v-model="curCustomer.contactTel" class="input-style"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="家属">
        <el-col :span="11">
          <el-input v-model="curCustomer.familyMember" class="input-style"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="备注">
        <el-col :span="11">
          <el-input v-model="curCustomer.attention" class="input-style"></el-input>
        </el-col>
      </el-form-item>
    </el-form>
    <el-button @click="optOne()" class="button-style dialog-opt-button">{{buttonOpt}}</el-button>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from "vue";
import http from '@/axios/http';
import qs from "qs";
import { ElMessage } from 'element-plus';

// 存放用户数据集合
let customerList = ref([]);

//报错提示
let errorMessage = ref("")

//模糊查询绑定的 客户名称
let queryName = ref("")

//对话框显示控制
let customerDialog = ref(false)

//客户信息，或者编辑已有客户的 绑定数据
let curCustomer = ref({});

//登记、修改客户信息弹出框的 标题和操作按钮  显示文字
let dialogTitle = reactive("")
let buttonOpt = reactive("")

//对话框操作类型：1：添加 2：编辑
let dialogOptType = reactive(1)
let size = 10; //当前显示多少行
let pageNum = 1; // 当前页码
let pageSize = 10; //每页显示行数

//当前页码信息
let pageContains = ref({})

//性别数组（其他字典值查询出来也是同样数据结构，使用方法类似）
let sexOptions = ref([
  {
    label: '男',
    value: 0
  },{
    label: '女',
    value: 1
  }
])

// 新增：客户状态筛选变量
let statusFilter = ref('all');

// 简单的身份证号格式验证（18位数字或最后一位为X）
function validateIdcard(idcard) {
  return /(^\d{17}(\d|X)$)|(^\d{15}$)/.test(idcard);
}

// 简单的联系电话格式验证（11位数字）
function validateContactTel(tel) {
  return /^1[3-9]\d{9}$/.test(tel);
}

// 验证年龄是否为合法数字
function validateAge(age) {
  return /^\d+$/.test(age) && parseInt(age) > 0 && parseInt(age) < 150;
}

//根据客户姓名模糊查询客户信息
function queryByName() {
  let param = {
    customerName: queryName.value
  }
  // 这里也可以根据statusFilter的值传递不同参数给后端进行筛选
  http.post('/lyy/get_customers_by', param).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result ==='success') {
          customerList.value = result.data;
        } else {
          errorMessage.value = result.error;
          ElMessage.error('查询失败，请稍后重试');
        }
      }
  )
}

//单击登录按钮事件
function showCustomerDialog() {
  dialogTitle = "客户入住登记";
  buttonOpt = "录入"
  //弹出客户信息对话框
  customerDialog.value = true;
  dialogOptType = 1 //设置当前操作类型标志是 录入
}

//关闭客户信息对话框
function closeCustomerDialog() {
  customerDialog.value = false;
}

//页面初始化
onMounted(
    () => {
      init();
    }
)

function init() {
  //查询所有用户信息
  getAllCustomers();
  //查询需要的字典（{标志1: 值1, 标志2: 值2}）
  //用的时候取 字典[字段值（字典标志）]
}

function getAllCustomers() {
  let params = {
    size: size,
    pageNum: pageNum,
    pageSize: pageSize,
    status: statusFilter.value
  }
  http.post('/lyy/get_all_customers', params).then((res) => {
    console.log(res.data);
    let result = res.data;
    // 返回结果传给 customerList
    if (result.result ==='success') {
      customerList.value = []; // 先置空
      pageContains.value = result.data;
      customerList.value = result.data.list;
    } else {
      errorMessage.value = result.error;
      ElMessage.error('获取客户列表失败，请稍后重试');
    }
  }).catch((error) => {
    console.error('请求接口发生错误:', error);
    ElMessage.error('网络请求出错，请检查网络连接');
  });
}

//格式化日期
function formatDate(row, column) {
  let data = row[column.property];
  if (data == null) {
    return null;
  }
  let dt = new Date(data);
  return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
  //+ ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds()
}

function recordOne() {
  // 表单验证
  if (!curCustomer.value.customerName) {
    ElMessage.warning('客户姓名不能为空');
    return;
  }
  if (!validateAge(curCustomer.value.customerAge)) {
    ElMessage.warning('年龄格式不正确或不在合理范围');
    return;
  }
  if (!validateIdcard(curCustomer.value.idcard)) {
    ElMessage.warning('身份证号格式不正确');
    return;
  }
  if (!validateContactTel(curCustomer.value.contactTel)) {
    ElMessage.warning('联系电话格式不正确');
    return;
  }

  let param = curCustomer.value;
  http.post('/lyy/add_one_customer', param).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result ==='success') {
          //关闭对话框
          closeCustomerDialog()
          //刷新客户列表
          getAllCustomers();
        } else {
          errorMessage.value = result.error;
          ElMessage.error('录入失败，请稍后重试');
        }
      }
  )
}

//显示编辑对话框
function showEditDialog(customerid) {
  //根据id查询客户信息
  getCustomerInfo(customerid)
  //显示对话框
  console.log(customerid)
  customerDialog.value = true;
  dialogTitle = "客户入住信息修改";
  buttonOpt = "修改"
  dialogOptType = 2 //设置当前操作类型标志是 修改
}

function getCustomerInfo(customerid) {
  let param = {
    customerid: customerid
  }
  http.post('/lyy/getcustomerby_id', qs.stringify(param)).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result ==='success') {
          curCustomer.value = result.data;
        } else {
          errorMessage.value = result.error;
          ElMessage.error('获取客户信息失败，请稍后重试');
        }
      }
  )
}

//删除客户
function removeOne(customerid) {
  let param = {
    customerid: customerid
  }
  http.post('/lyy/removecustomer_by_id', qs.stringify(param)).then(
      (res) => {
        let result = res.data;
        // 返回结果传给 customerList
        if (result.result ==='success') {
          getAllCustomers();
        } else {
          errorMessage.value = result.error;
          ElMessage.error('删除失败，请稍后重试');
        }
      }
  )
}

function editOne() {
  // 表单验证
  if (!curCustomer.value.customerName) {
    ElMessage.warning('客户姓名不能为空');
    return;
  }
  if (!validateAge(curCustomer.value.customerAge)) {
    ElMessage.warning('年龄格式不正确或不在合理范围');
    return;
  }
  if (!validateIdcard(curCustomer.value.idcard)) {
    ElMessage.warning('身份证号格式不正确');
    return;
  }
  if (!validateContactTel(curCustomer.value.contactTel)) {
    ElMessage.warning('联系电话格式不正确');
    return;
  }

  let param = curCustomer.value;
  http.post('/lyy/modifycustomerby_id', param).then(
      (res) => {
        let result = res.data;
        if (result.result ==='success') {
          closeCustomerDialog();
          getAllCustomers();
        } else {
          errorMessage.value = result.error;
          ElMessage.error('修改失败，请稍后重试');
        }
      }
  )
}

function optOne() {
  if (dialogOptType === 1) {
    recordOne()
  } else if (dialogOptType === 2) {
    editOne()
  }
}

//分页处理
const handlePageChange = (pageNum1) => {
  pageNum = pageNum1
  getAllCustomers()
}

const handleSizeChange = (pageSize1) => {
  pageSize = pageSize1
  getAllCustomers()
}

watch(statusFilter, () => {
  getAllCustomers();
});
</script>

<style scoped>

</style>